﻿/*
    上传资源模板
*/
var config =
{
    fileNameContainer: "<div id='fileName' />",
    progressBar: "<div class='progress' style='margin:3px 0 8px 0px; padding:0;'><div class='bar' style='width:0%'></div></div>",
    progressFullBar: "<div class='progress' style='margin:3px 0 8px 0px; padding:0;'><div class='bar' style='width:100%'></div></div>",
    startButton: "<input type='button' value='开始' style='display:none'/>",
    cancelButton: "<input type='button' value='取消' style='display:none'/>",
    deleteButton: "<input type='button' value='删除' style='margin:0px 0px 0px 5px'/>",
    upButton: "<input type='button'  value='向上' style='margin:0px 0px 0px 0px'/>",
    calculateCompleteText: "文件分析完成，正在上传。。。",
    uploadCompleteText: "... 上传完成！",
    calculatingText: "正在分析文件：",
    versionLowTip: "当前浏览器版本过低，请使用高版本。"
}


var initUpload = function (paras) {
    //上传操作
    jQuery('#' + paras.fileID).fileupload({
        dataType: "json",
        url: paras.url,
        limitConcurrentUploads: 10,
        sequentialUploads: false,
        progressInterval: 100,
        maxChunkSize: 512 * 1024,
        add: function (e, data) {

            //data.context = '';
            var btnStart = jQuery(config.startButton).bind("click", function () {
                data.submit();
            })//.appendTo(data.context);

            //hash计信息
            var span = jQuery("<span></span>").appendTo(data.context);
            handlefile(btnStart, data.files[0]);
        },
        done: function (e, data) {
            //alert("上传成功,上传资源地址:" + data.result.Path);
            //alert("上传成功,上传资源组:" + data.result.Group);
            var imgPath = 'http://localhost:11111/' + 'FileManagement/DownLoad?resourceID=' + data.result.ResourceID
            jQuery('#' + paras.coverID).attr('src', imgPath);
            //jQuery('#div-parent').append("</br><a id='file-parent'>" + data.result.Path + "<a>");
            //var imgPath = 'http://localhost:11111/' + 'FileManagement/DownLoad?resourceID=' + data.result.ResourceID 
            //jQuery('#video-parent').attr('src', imgPath);
            //jQuery('#img-parent').attr('src', imgPath);
            //jQuery('#img-parent').attr('target', data.result.ResourceID);
     //       if (window.dicHash[data.files[0].name] != null &&
     //window.dicHash[data.files[0].name] != undefined &&
     //data.files[0].name != null && data.files[0].name != undefined)
                       
        },
        //进度条
        progressall: function (e, data) {
            //var progress = parseInt(data.loaded / data.total * 100, 10);
            //jQuery('#overallbar').css('width', progress + '%');
        },
        progress: function (e, data) {
            //var progress = parseInt(data.loaded / data.total * 100, 10);
            //data.context.find('.bar').css('width', progress + '%');
        }
    });

    //hash计算
    window.dicHash = new Array();

    if ((typeof File !== 'undefined') && !File.prototype.slice) {
        if (File.prototype.webkitSlice) {
            File.prototype.slice = File.prototype.webkitSlice;
        }

        if (File.prototype.mozSlice) {
            File.prototype.slice = File.prototype.mozSlice;
        }
    }

    if (!window.File || !window.FileReader || !window.FileList || !window.Blob || !File.prototype.slice) {
        alert(config.versionLowTip);
    }

    function hash_file(file, workers) {
        var i, buffer_size, block, threads, reader, blob, handle_hash_block, handle_load_block;

        handle_load_block = function (event) {
            for (i = 0; i < workers.length; i += 1) {
                threads += 1;
                workers[i].postMessage({
                    'message': event.target.result,
                    'block': block
                });
            }
        };
        handle_hash_block = function (event) {
            threads -= 1;

            if (threads === 0) {
                if (block.end !== file.size) {
                    block.start += buffer_size;
                    block.end += buffer_size;

                    if (block.end > file.size) {
                        block.end = file.size;
                    }
                    reader = new FileReader();
                    reader.onload = handle_load_block;
                    blob = file.slice(block.start, block.end);

                    reader.readAsArrayBuffer(blob);
                }
            }
        };
        buffer_size = 64 * 16 * 1024;
        block = {
            'file_size': file.size,
            'start': 0
        };

        block.end = buffer_size > file.size ? file.size : buffer_size;
        threads = 0;

        for (i = 0; i < workers.length; i += 1) {
            workers[i].addEventListener('message', handle_hash_block);
        }
        reader = new FileReader();
        reader.onload = handle_load_block;
        blob = file.slice(block.start, block.end);

        reader.readAsArrayBuffer(blob);
    }

    function handle_worker_event(name, p) {
        return function (event) {
            if (event.data.result) {
                p.next().next().text(config.calculateCompleteText);
                window.dicHash[name] = event.data.result;
                if (p) {
                    p.click();
                }

            } else {
                p.next().next().text(config.calculatingText + (event.data.block.end * 100 / event.data.block.file_size).toFixed(2) + '%');
            }
        };
    }


    function handlefile(p, f) {
        event.stopPropagation();
        event.preventDefault();
        var file, worker;
        file = f;
        //计算sha1
        worker = new Worker('/Scripts/hash/sha1.js');
        worker.addEventListener('message', handle_worker_event(file.name, p));
        hash_file(file, [worker]);
    }

    function formatFileSize(bytes) {
        if (typeof bytes !== 'number') {
            return '';
        }
        if (bytes >= 1000000000) {
            return (bytes / 1000000000).toFixed(2) + ' GB';
        }
        if (bytes >= 1000000) {
            return (bytes / 1000000).toFixed(2) + ' MB';
        }
        if (bytes >= 1000) {
            return (bytes / 1000).toFixed(2) + ' KB';
        }
        return bytes + "B";
    }

    function deleteFile(resourceID, deleteUrl) {
        var result = false;
        jQuery.ajax({
            async: false,
            type: "POST",
            url: deleteUrl,
            data: "resourceID=" + resourceID,//"fileHash=" + fileHash + "&fileName=" + fileName,
            success: function (data) {
                if (data == "True") {
                    result = true;
                }
                else {
                    alert("删除失败,请重试！");
                }
            },
            error: function (msg) {
                alert(msg);
            }
        });
        return result;
    }
};